package com.vegetable.modules.service.finance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.finance.PaymentLog;
import com.vegetable.modules.entity.finance.PaymentPurchase;
import com.vegetable.modules.mapper.finance.PaymentPurchaseMapper;
import com.vegetable.modules.service.finance.IPaymentLogService;
import com.vegetable.modules.service.finance.IPaymentPurchaseService;
import com.vegetable.modules.service.finance.PaymentProcessService;
import com.vegetable.modules.service.finance.UnionPayService;
import com.vegetable.modules.service.wx.WxCpMessageService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import com.vegetable.modules.service.finance.config.PaymentProcessConfig;
import com.vegetable.modules.service.wx.config.WxApprovalConfig;

/**
 * 付款流程服务实现类
 *
 * @author Qoder
 */
@Slf4j
@Service
public class PaymentProcessServiceImpl implements PaymentProcessService {

    @Autowired
    private IPaymentPurchaseService paymentPurchaseService;

    @Autowired
    private PaymentPurchaseMapper paymentPurchaseMapper;

    @Autowired
    private UnionPayService unionPayService;

    @Autowired
    private IPaymentLogService paymentLogService;

    @Autowired
    private WxCpMessageService wxCpMessageService;
    
    @Value("${wechat.cp.admin.userIds:XiaoQin18754420999}")
    private String adminUserIds;

    @Autowired
    private PaymentProcessConfig paymentProcessConfig;
    
    @Autowired
    private WxApprovalConfig wxApprovalConfig;

    @Override
    public R processApprovalAndPayment(Long paymentId, boolean isApproved, String remark) {
        try {
            log.info("开始处理审批结果，付款ID: {}, 审批结果: {}", paymentId, isApproved);

            // 获取付款详情
            PaymentPurchase payment = paymentPurchaseMapper.selectById(paymentId);
            if (payment == null) {
                return R.fail("付款记录不存在");
            }

            if (isApproved) {
                // 检查是否启用自动支付
                if (paymentProcessConfig.isAutoExecutePayment()) {
                    // 审批通过，执行支付
                    return executePayment(payment);
                } else {
                    // 不自动执行支付，只更新状态
                    payment.setApprovalState(2); // 2表示审批通过
                    paymentPurchaseMapper.updateById(payment);

                    log.info("付款审批通过，等待手动执行支付，付款ID: {}", paymentId);
                    return R.success("付款审批已通过，等待手动执行支付");
                }
            } else {
                // 审批拒绝，更新状态
                payment.setApprovalState(3); // 3表示审批拒绝
                paymentPurchaseMapper.updateById(payment);

                log.info("付款审批被拒绝，付款ID: {}", paymentId);
                return R.success("付款审批已拒绝");
            }
        } catch (Exception e) {
            log.error("处理审批结果时发生异常", e);
            return R.fail("处理失败: " + e.getMessage());
        }
    }

    /**
     * 执行支付
     *
     * @param payment 付款信息
     * @return 支付结果
     */
    private R executePayment(PaymentPurchase payment) {
        try {
            // 调用银联支付服务（使用原有的方法，不传递收款人信息）
            R payResult = unionPayService.executeSinglePayment(payment);

            if (payResult.getCode() == 0) {
                // 支付成功
                payment.setState(1); // 1表示实际已付
                payment.setApprovalState(2); // 2表示审批通过
                payment.setRemitTime(new Date()); // 设置打款时间
                paymentPurchaseMapper.updateById(payment);

                log.info("支付成功，付款ID: {}", payment.getId());
                return R.success("支付成功");
            } else {
                // 支付失败
                payment.setApprovalState(2); // 2表示审批通过，但支付失败
                paymentPurchaseMapper.updateById(payment);

                log.error("支付失败，付款ID: {}, 错误信息: {}", payment.getId(), payResult.getMsg());
                return R.fail("支付失败: " + payResult.getMsg());
            }
        } catch (Exception e) {
            log.error("执行支付时发生异常", e);
            return R.fail("支付异常: " + e.getMessage());
        }
    }

}